<?php

namespace App\Models;

use EasyWeChat;

class WechatMenus extends BaseModel
{
    protected $table = "wechat_menus";

    protected $rules = [
        'title' => 'required|between:1,8',
        'admin_id' => 'required',
    ];

    protected $message = [
        'title.required' => '菜单名称必须填写',
        'title.between' => '菜单名称不合法必须1-8个字',
        'admin_id.required' => '获取商户信息失败',
    ];

    /**
     * 获取分类详细信息
     * @param  milit $id 分类ID或标识
     * @param  boolean $field 查询字段
     * @return array     分类信息
     */
    public function getInfo($id)
    {
        return $this->_getOneById($id);
    }

    /**
     * 类别列表
     *
     * @param array $where 检索条件
     * @return array 数组结构的返回结果
     */
    public function getDiymenuList($where,  $sort = 'asc', $limit = '')
    {
        $fields = 'id,title,type,title,url,appid,pagepath';
        return $this->multiSelect($fields)->multiWhere($where)->multiOrder(['sort'=>$sort])->take($limit)->get();
    }

    /**
     * 总数
     * @param array $where 检索条件
     * @return array 数组结构的返回结果
     */
    public function getDiymenuCount($where, $sort = 'asc', $limit = '')
    {
        $fields = 'id';
        return $this->multiSelect($fields)->multiWhere($where)->multiOrder(['sort'=>$sort])->take($limit)->count();
    }


    /**
     * 获取分类树，指定分类则返回指定分类极其子分类，不指定则返回所有分类树
     * @param  integer $id 分类ID
     * @param  string $field 查询字段
     * @return array          分类树
     */
    public function getTree($id = 0, $field = '*')
    {
        /* 获取当前分类信息 */
        if ($id) {
            $info = $this->getInfo($id);
            $id = $info['id'];
        }
        $list = $this->_getList(['admin_id' => is_login()],'id,pid,is_show,title,sort',['sort'=>'asc']);
        if ($list) {
            $list = $list->toArray();
        }
        $list = list_to_tree($list, $pk = 'id', $pid = 'pid', $child = '_', $root = $id);

        /* 获取返回数据 */
        if (isset($info)) { //指定分类则返回当前分类极其子分类
            $info['_'] = $list;
        } else { //否则返回所有分类
            $info = $list;
        }

        return $info;
    }

    public function checkMenuAdd()
    {
        if (!request('pid')) {
            $res = $this->_count(['pid' => 0, 'admin_id' => is_login()], 'id');
            if ($res >= 3) {
                $this->error = '一级菜单最多只能添加3个！';
                return false;
            }
            return true;
        }
        $res = $this->_count(['pid' => request('pid'), 'admin_id' => is_login()], 'id');
        if ($res >= 5) {
            $this->error = '二级菜单最多只能添加5个！';
            return false;
        }
        return true;
    }

    public function getMenuTree()
    {
        $menu = $this->_getList(['admin_id' => is_login()])->toArray();
        $menu = childTree($menu, 0, 'id', 'pid');
        $menu = array_merge([0 => ['id' => 0, 'title' => '顶级菜单', 'prefix' => '']], $menu);
        return $menu;
    }

    public function operate($type)
    {
        $to = request('to');
        $from = request('from');
        $operate = $type == 'move' ? '移动' : ($type == 'merge' ? '合并' : '');
        if (!$operate) {
            $this->error = '参数错误！';
            return false;
        }
        if ($type == 'move') {
            $res = $this->_update(['id' => $from], ['pid' => $to]);
            if (!$res) {
                $this->error = '分类移动失败！';
                return false;
            }
        }
        if ($type == 'merge') {
            //删除被合并的分类
            $this->_del(['id' => $from]);
        }
        //记录行为
        return '分类' . $operate . '成功！';
    }

    public function getModules()
    {
        return [
            [
                'title' => '商城入口',
                'url' => 'shop/entrance/1',
            ],
            [
                'title' => '管理入口',
                'url' => 'manager/login.html',
            ],
        ];
    }

    public function getXcx()
    {
        return [
            [
                'title' => '趣订水商户平台',
                'appid' => 'wxd4c437c85a0b0f22',
            ],
            [
                'title' => '趣订水演示版',
                'appid' => 'wxe3483f5608c83ce5',
            ],
        ];
    }

    public function addOrUpdate()
    {
        $url = trim(request('url'));
        $reply_content = trim(request('reply_content'));
        $appid = trim(request('appid'));
        request('title') && $data['title'] = trim(request('title'));
        request('pid') && $data['pid'] = trim(request('pid'));
        request('type') && $data['type'] = intval(request('type'));
        $data['admin_id'] = is_login();
        $this->_start();
        if (request('type')) {
            if (!request('title')) {
                $this->error = '请填写菜单名称!';
                return false;
            }
            switch ($data['type']) {
                case 1:
                    $reply_content = str_replace("\r\n", "\n", $reply_content);
                    $data['reply_content'] = strip_tags($reply_content,"\n");
                    break;
                case 2:
                    $data['url'] = $url;
                    break;
                case 3:
                    $data['appid'] = $appid;
                    $data['url'] = trim(request('bak_url'));;
                    $data['pagepath'] = trim(request('pagepath'));;
                    break;
            }
        }
        request()->has('sort') && $data['sort'] = trim(request('sort'));
        request('is_show') && $data['is_show'] = trim(request('is_show'));
        if (request('id')) {
            $data['id'] = trim(request('id'));
            if (request('old_pid') && request('old_pid') != $data['pid']) {
                $res = $this->checkMenuAdd();
                if (!$res) {
                    $this->_rollBack();
                    return false;
                }
            }
        } else {
            $res = $this->checkMenuAdd();
            if (!$res) {
                $this->_rollBack();
                return false;
            }
        }
        if (!$this->_validate($data)) {
            $this->_rollBack();
            return false;
        }
        $res = $this->_save($data);
        if (!$res) {
            $this->_rollBack();
            $this->error = '保存失败!';
            return false;
        }
        $this->_commit();
        return $res;
    }

    public function del()
    {
        $id = request('id');
        if (!$id) {
            $this->error = '请选择要操作的数据!';
            return false;
        }
        $child = $this->_getList(['pid' => $id])->toArray();
        if (!empty($child)) {
            $this->error = '请先删除该菜单下的子菜单';
            return false;
        }
        $res = $this->_del(['id' => $id]);
        if (!$res) {
            $this->error = '删除菜单失败!';
            return false;
        }
        //记录行为
        return '删除菜单成功';
    }

    public function sendMenu()
    {
        $aid = 1;
        $wechatSet = new WechatSet();
        $info = $wechatSet->_getOne(['admin_id' => $aid]);
        $appid = $info['wx_app_id'];
        $secret = $info['wx_app_secret'];
        if (!request()->method('GET')) {
            $this->error = '非法操作!';
            return false;
        }
        $url_get = 'https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid=' .
            $appid . '&secret=' . $secret;
        $json = json_decode($this->curlGet($url_get));
        if (isset($json->errcode)) {
            $this->error = '获取access_token发生错误，' . $json->errmsg;
            return false;
        }
        $data = '{"button":[';
        $class = $this->getDiymenuList(['pid' => 0, 'is_show' => 1,'admin_id'=>$aid], 'asc', 3);
        $kcount = $this->getDiymenuCount(['pid' => 0, 'is_show' => 1,'admin_id'=>$aid], 'asc', 3);
        $k = 1;
        foreach ($class as $key => $vo) {
            //主菜单
            $data .= '{"name":"' . $vo['title'] . '",';
            $c = $this->getDiymenuList(['pid' => $vo['id'], 'is_show' => 1,'admin_id'=>$aid], 'desc', 5)->toArray();
            $count = $this->getDiymenuCount(['pid' => $vo['id'], 'is_show' => 1,'admin_id'=>$aid],'desc', 5);
            //子菜单
            if ($c != false) {
                $data .= '"sub_button":[';
            } else {
                if (!$vo['url']) {
                    $data .= '"type":"click","key":"' . $vo['id'] . '"';
                } else {
                    if ($vo['type'] == 3) {
                        $data .= '"type":"miniprogram","url":"'.$vo['url'].'","appid":"' . $vo['appid'] . '","pagepath":"' . $vo['pagepath'] . '"';
                    } else {
                        $data .= '"type":"view","url":"' . $vo['url'] . '"';
                    }
                }
            }
            $i = 1;
            foreach ($c as $voo) {
                if ($i == $count) {
                    if ($voo['url']) {
                        if ($voo['type'] == 3) {
                            $data .= '{"type":"miniprogram","name":"' . $voo['title'] . '","url":"'.$voo['url'].'","appid":"' . $voo['appid'] . '","pagepath":"' . $voo['pagepath'] . '"}';
                        } else {
                            $data .= '{"type":"view","name":"' . $voo['title'] . '","url":"' . $voo['url'] . '"}';
                        }
                    } else {
                        $data .= '{"type":"click","name":"' . $voo['title'] . '","key":"' . $voo['id'] . '"}';
                    }
                } else {
                    if ($voo['url']) {
                        if ($voo['type'] == 3) {
                            $data .= '{"type":"miniprogram","name":"' . $voo['title'] . '","url":"'.$voo['url'].'","appid":"' . $voo['appid'] . '","pagepath":"' . $voo['pagepath'] . '"},';
                        } else {
                            $data .= '{"type":"view","name":"' . $voo['title'] . '","url":"' . $voo['url'] . '"},';
                        }
                    } else {
                        $data .= '{"type":"click","name":"' . $voo['title'] . '","key":"' . $voo['id'] . '"},';
                    }
                }
                $i++;
            }
            if ($c != false) {
                $data .= ']';
            }
            if ($k == $kcount) {
                $data .= '}';
            } else {
                $data .= '},';
            }
            $k++;
        }
        $data .= ']}';
        file_get_contents('https://api.weixin.qq.com/cgi-bin/menu/delete?access_token=' . $json->access_token);
        $url = 'https://api.weixin.qq.com/cgi-bin/menu/create?access_token=' . $json->access_token;
        $rt = $this->api_notice_increment($url, $data);
        if (!$rt['rt']) {
            $this->error = '操作失败!';
            return false;
        }
        return '操作成功!';
    }

    public function api_notice_increment($url, $data)
    {
        $ch = curl_init();
        $header = "Accept-Charset: utf-8";
        curl_setopt($ch, CURLOPT_URL, $url);
        curl_setopt($ch, CURLOPT_CUSTOMREQUEST, "POST");
        curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
        curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, false);
        //curl_setopt($curl, CURLOPT_HTTPHEADER, $header);
        curl_setopt($ch, CURLOPT_USERAGENT, 'Mozilla/5.0 (compatible; MSIE 5.01; Windows NT 5.0)');
        curl_setopt($ch, CURLOPT_FOLLOWLOCATION, 1);
        curl_setopt($ch, CURLOPT_AUTOREFERER, 1);
        curl_setopt($ch, CURLOPT_POSTFIELDS, $data);
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
        $tmpInfo = curl_exec($ch);
        $errorno = curl_errno($ch);
        if ($errorno) {
            return ['rt' => false, 'errorno' => $errorno];
        } else {
            $js = json_decode($tmpInfo, 1);
            if ($js['errcode'] == '0') {
                return ['rt' => true, 'errorno' => 0];
            } else {
                $this->error = '发生错误：错误代码' . $js['errcode'] . ',微信返回错误信息：' . $js['errmsg'];
                return false;
            }
        }
    }

    public function curlGet($url)
    {
        $data = '';
        $ch = curl_init();
        $header = "Accept-Charset: utf-8";
        curl_setopt($ch, CURLOPT_URL, $url);
        curl_setopt($ch, CURLOPT_CUSTOMREQUEST, "GET");
        curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
        curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, false);
        //curl_setopt($curl, CURLOPT_HTTPHEADER, $header);
        curl_setopt($ch, CURLOPT_USERAGENT, 'Mozilla/5.0 (compatible; MSIE 5.01; Windows NT 5.0)');
        curl_setopt($ch, CURLOPT_FOLLOWLOCATION, 1);
        curl_setopt($ch, CURLOPT_AUTOREFERER, 1);
        curl_setopt($ch, CURLOPT_POSTFIELDS, $data);
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
        $temp = curl_exec($ch);
        return $temp;
    }

}
